<template>
  <el-row type="flex" justify="space-between" align="middle" style="height: 40px;width:100%">
    <el-col>
      <span>{{ treeNode.name }}</span>
    </el-col>
    <el-col :span="4">
      <el-row type="flex" justify="end">
        <!-- 两个内容 -->
        <el-col>{{ treeNode.manager }}</el-col>
        <!-- 下拉菜单 -->
        <el-col>
          <el-dropdown @command="operateDepts">
            <!-- 显示内容 -->
            <span>
              操作
              <i class="el-icon-arrow-down"/>
            </span>
            <!-- 下拉内容 -->
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="add">添加子部门</el-dropdown-item>
              <!-- 编辑部门和删除部门只会在子节点上显示 -->
              <el-dropdown-item v-if="!isRoot" command="edit">编辑部门</el-dropdown-item>
              <el-dropdown-item v-if="!isRoot" command="del">删除部门</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-col>
      </el-row>
    </el-col>
  </el-row>
</template>

<script>
import { delDepartments } from '@/api/departments'
export default {
  name: 'TreeNode',
  props: {
    treeNode: {
      type: Object,
      required: true
    },
    isRoot: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {}
  },
  methods: {
    operateDepts(type) {
      if (type === 'add') {
        // 添加子部门
        // 传treeNode，代表在当前部门下创建子部门
        this.$emit('addDepts', this.treeNode)
      } else if (type === 'edit') {
        // 编辑部门
        this.$emit('editDepts', this.treeNode)
      } else {
        // 删除部门的操作
        this.$confirm('确定要删除子部门吗？', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            return delDepartments(this.treeNode.id)
          })
          .then(() => {
            // 删除成功了走这个区间
            // 因为上面是return的一个promise 所以这里用.then来处理
            this.$emit('delDepts')
            this.$message.success('删除部门成功')
          })
          .catch(err => {
            console.log('cancel' + err)
          })
      }
    }
  }
}
</script>
<style lang='less' scoped>
</style>
